package idv.loveloser.servlet;

import idv.loveloser.dao.MdlRoleAssignments;
import idv.loveloser.dao.MdlRoleAssignmentsDAO;
import idv.loveloser.dao.MdlUser;
import idv.loveloser.dao.MdlUserDAO;
import idv.loveloser.dao.MdlWebservicesSessions;
import idv.loveloser.dao.MdlWebservicesSessionsDAO;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class Login extends HttpServlet {
	private MdlUserDAO userDao = new MdlUserDAO();
	private MdlWebservicesSessionsDAO sessionDao = new MdlWebservicesSessionsDAO();
	private MdlRoleAssignmentsDAO roleAssignmentDAO = new MdlRoleAssignmentsDAO();
	/**
	 * Constructor of the object.
	 */
	public Login() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		MdlWebservicesSessions session =new MdlWebservicesSessions();
		//response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		
		String salt=SystemSets.getSalt();
		boolean hasRight=false;
		MdlUser user=null;
		List<MdlUser> users=userDao.findByUsername(username);
		if(users!=null)
			user=users.get(0);
		List<MdlRoleAssignments> roles=roleAssignmentDAO.findByUserid(user.getId());
		for(int index=0;index<roles.size();index++){
			MdlRoleAssignments role =roles.get(index);
			if(role.getRoleid()<4)
				hasRight=true;
		}
//		String passwordMd5=doMd5(password);
		if(user.getPassword().equals(encryPassword(password,salt))){
			session.setUserid(user.getId());
			session.setSessionbegin(System.currentTimeMillis());
			session.setId(user.getId());
			session.setVerified(true);
			session.setIp(request.getRemoteAddr());
			session.setSessionend(0L);
			session.setSessionkey(getSessionKey());
			sessionDao.save(session);
			user.setLastlogin(System.currentTimeMillis());
			userDao.save(user);
			Gson gson = new Gson();
			JsonObject json = new JsonObject();
			json.addProperty("sessionKey", session.getSessionkey());
			json.addProperty("client", session.getId());
			json.addProperty("hasRight", hasRight);
			out.println(json.toString());
		}
		
		out.flush();
		out.close();
	}
	public static String toHex(byte b){
		return (""+"0123456789abcdef".charAt(0xf&b>>4)+"0123456789abcdef".charAt(b&0xf));} 
	private String encryPassword(String password,String salt){
		String tempStr = password+salt;
		String returStr="";
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(tempStr.getBytes());
			byte[] temp =md5.digest();
//			Base64 base64 = new Base64();
//			byte[] result =base64.encode(temp);
			for(int index=0;index<temp.length;index++){
				returStr+=toHex(temp[index]);
			}
//			System.out.println(returStr);
			
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returStr;
	}
	private String doMd5(String tempStr){
		String returnStr="";
		try {
			MessageDigest md5= MessageDigest.getInstance("MD5");
			md5.update(tempStr.getBytes());
			byte[] result =md5.digest();
			returnStr = new String(result);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returnStr;
	} 
	private String getSessionKey(){
		
		String time= System.currentTimeMillis()+"";
		time.subSequence(0, 9);
		return time.substring(0, 9);
	}
	private byte[] xorWithKey(byte[] a, byte[] key) {
		byte[] out = new byte[a.length];
		for (int i = 0; i < a.length; i++) {
			out[i] = (byte) (a[i] ^ key[i%key.length]);
		}
		return out;
	} 
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
